package com.zh.controller;

import com.aliyuncs.utils.StringUtils;
import com.zh.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 阿里云短信服务
 */
@RestController
@CrossOrigin  // 跨域支持
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 发送短信验证吗
     * @param phone
     * @return
     */
    @GetMapping("/send-sms/{phone}")
    public String sendSms(@PathVariable String phone){
        // 先根据手机号去redis中获取编码值
        String code = redisTemplate.opsForValue().get(phone);
        System.out.println("code:"+code);
        System.out.println(StringUtils.isEmpty(code));
        boolean isSucceed = false;
        if(!StringUtils.isEmpty(code)){
            // 验证吗已存在
            return phone+":"+code+"已存在,还没有过期";
        }else{
            code = UUID.randomUUID().toString().substring(0, 4);

            Map<String, Object> map = new HashMap<>();
            map.put("code",code);
            isSucceed = smsService.sendSms(phone, "SMS_204985345", map);
        }

        System.out.println("isSucceed:"+isSucceed);
        if (isSucceed){
            // 存到redis中，设置过期时间为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return phone+":"+code+"发送成功";
        }
        return phone+":"+code+"发送失败";
    }

}
